package com.woniu.tmscommons.interceptor;


import com.woniu.tmscommons.anno.RequirePerms;
import com.woniu.tmscommons.exception.UnAuthorizationException;
import com.woniu.tmscommons.feign.FeignAuthService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * 拦截器：controller中的方法、静态资源
 */

@Slf4j
@Component
public class AuthInterceptor implements HandlerInterceptor {
    // 懒注入：在创建AuthInterceptor对象时不注入，在使用FeignAuthService才注入
    @Lazy
    @Resource
    private FeignAuthService feignAuthService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        log.debug("拦截器执行拦截");
        if (handler instanceof HandlerMethod){
            HandlerMethod handlerMethod = (HandlerMethod) handler;
            // 获取方法
            Method method = handlerMethod.getMethod();
            log.debug(method.getName());
            // 判断方法上面是否有权限注解
            if (method.isAnnotationPresent(RequirePerms.class)){
                // 获取到注解
                RequirePerms requirePerms = method.getAnnotation(RequirePerms.class);
                // 获取到注解中的值
                String perms = requirePerms.value();
                log.debug(perms);
                // 获取到当前用户信息
                String token = request.getHeader("authorization");
                // 获取权限信息
                List<String> permsList = feignAuthService.findPerms(token).getData();
                // 判断
                if (!permsList.contains(perms)){
                    // 没权限  抛异常
                    throw new UnAuthorizationException("没权限操作");
                }
            }
        }
        return true;
    }
}
